package utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class jdbcUtils {
    public static DruidDataSource druidDataSource;
    private static Properties properties;
    static {
        //创建数据库连接池
        try {
            properties=new Properties();
            InputStream inputStream = jdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(inputStream);
            druidDataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection() {
        Connection conn=null;
        try {
            conn=druidDataSource.getConnection();
            String url=properties.getProperty("url");
            System.out.printf("----------%s数据库连接成功-----------\n",url);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    /***
     * 关闭数据库连接
     * @param conn 连接对象
     */
    public static void Colse(Connection conn){
        if (conn!=null){
            try {
                conn.close();
                System.out.printf("数据库连接关闭");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
